class GroupManager {
    constructor() {
        this.groups = new Map(); // 存储群聊信息 groupId -> { members: Set<socketId>, messages: [], playbackState: { isPlaying, song: { id, name, time, author, picUrl }, progress } }
    }

    // 创建群聊
    createGroup(groupId) {
        if (!this.groups.has(groupId)) {
            this.groups.set(groupId, {
                members: new Set(),
                messages: [],
                playbackState: {
                    isPlaying: false,
                    song: {
                        id: null,
                        name: null,
                        time: null,
                        author: null,
                        picUrl: null
                    },
                    progress: 0
                }
            });
            console.log(`创建新群聊: ${groupId}`);
        }
    }

    // 加入群聊
    joinGroup(groupId, socketId) {
        this.createGroup(groupId);
        const group = this.groups.get(groupId);
        group.members.add(socketId);
        console.log(`用户 ${socketId} 加入群聊 ${groupId}，当前成员数: ${group.members.size}`);
    }

    // 离开群聊
    leaveGroup(groupId, socketId) {
        const group = this.groups.get(groupId);
        if (group) {
            group.members.delete(socketId);
            console.log(`用户 ${socketId} 离开群聊 ${groupId}，剩余成员数: ${group.members.size}`);

            // 如果群聊没有成员了，只修改播放状态
            if (group.members.size === 0) {
                group.playbackState.isPlaying = false;
                console.log(`群聊 ${groupId} 已暂停播放`);
            }
        }
    }

    // 添加消息
    addMessage(groupId, message) {
        const group = this.groups.get(groupId);
        if (group) {
            group.messages.push(message);
            // 只保留最近的100条消息
            if (group.messages.length > 100) {
                group.messages = group.messages.slice(-100);
            }
            console.log(`群聊 ${groupId} 收到新消息，当前消息数: ${group.messages.length}`);
        }
    }

    // 获取群聊消息
    getGroupMessages(groupId) {
        const group = this.groups.get(groupId);
        return group ? group.messages : [];
    }

    // 获取群聊成员
    getGroupMembers(groupId) {
        const group = this.groups.get(groupId);
        return group ? Array.from(group.members) : [];
    }

    // 检查群聊是否存在
    hasGroup(groupId) {
        return this.groups.has(groupId);
    }

    // 检查用户是否是群聊成员
    isMember(groupId, socketId) {
        const group = this.groups.get(groupId);
        return group ? group.members.has(socketId) : false;
    }

    // 获取群聊信息
    getGroupInfo(groupId) {
        const group = this.groups.get(groupId);
        return group ? {
            groupId,
            memberCount: group.members.size,
            messageCount: group.messages.length
        } : null;
    }

    // 获取群聊成员信息列表
    getGroupMembersInfo(groupId, io) {
        const group = this.groups.get(groupId);
        if (!group) return [];

        return Array.from(group.members).map(socketId => {
            const socket = io.sockets.sockets.get(socketId);
            if (socket && socket.user) {
                return {
                    avatar: socket.user.avatar || null,
                    name: socket.user.name,
                    email: socket.user.email || null,
                    isVisitor: socket.user.isVisitor ? true : null
                };
            }
            return null;
        }).filter(member => member !== null);
    }

    // 获取所有群聊信息
    getAllGroupsInfo(io) {
        const groupsInfo = [];
        for (const [groupId, group] of this.groups) {
            groupsInfo.push({
                groupId,
                members: this.getGroupMembersInfo(groupId, io),
                memberCount: group.members.size,
                messageCount: group.messages.length
            });
        }
        return groupsInfo;
    }

    // 获取群聊播放状态
    getPlaybackState(groupId) {
        const group = this.groups.get(groupId);
        return group ? group.playbackState : null;
    }

    // 获取所有群聊的播放状态
    getAllPlaybackStates() {
        const states = [];
        for (const [groupId, group] of this.groups) {
            // 如果群聊有成员，则保持当前的播放状态
            // 如果群聊没有成员，则设置isPlaying为false
            const isPlaying = group.members.size > 0 ? group.playbackState.isPlaying : false;
            states.push({
                groupId,
                isPlaying: isPlaying,
                song: group.playbackState.song,
                progress: group.playbackState.progress
            });
        }
        return states;
    }

    // 获取在线但未加入任何群聊的用户列表
    getOnlineUsersNotInGroups(io) {
        // 获取所有已连接的socket
        const allSockets = Array.from(io.sockets.sockets.values());

        // 获取所有群聊中的成员socketId
        const groupMemberSocketIds = new Set();
        for (const group of this.groups.values()) {
            for (const socketId of group.members) {
                groupMemberSocketIds.add(socketId);
            }
        }

        // 过滤出未加入任何群聊的用户
        return allSockets
            .filter(socket => !groupMemberSocketIds.has(socket.id) && socket.user)
            .map(socket => ({
                avatar: socket.user.avatar || null,
                name: socket.user.name,
                email: socket.user.email || null,
                isVisitor: socket.user.isVisitor ? true : null
            }));
    }

    // 更新群聊播放状态
    updatePlaybackState(groupId, newState) {
        const group = this.groups.get(groupId);
        if (group) {
            // 直接更新 isPlaying 状态
            if (typeof newState.isPlaying !== 'undefined') {
                group.playbackState.isPlaying = newState.isPlaying;
            }

            // 更新其他状态
            if (newState.song) {
                group.playbackState.song = {
                    ...group.playbackState.song,
                    ...newState.song
                };
            }

            if (typeof newState.progress !== 'undefined') {
                group.playbackState.progress = newState.progress;
            }

            return true;
        }
        return false;
    }
}

module.exports = new GroupManager(); 